/**
 * Created by liguangsong on 16/8/15.
 */
$(document).ready(function() {
    showShoppingCarList();
    addCalcButtonClickEvent();
    bindInputKeyUp();
    bindInputNotNull();
    modifyTotalPrice();
    clickPayButton();
});



function showShoppingCarList() {
    var localData = getLocalData();
    var data = {
        "shoppingCart": localData
    };
    var template = $("#car_template").html();
    Mustache.parse(template);
    var shoppingCarInfo = Mustache.render(template, addCartDataId(data));
    $(".shop_cart thead").after(shoppingCarInfo);
}


function addCartDataId(data) {
    _.times(data.shoppingCart.length, function(index) {
        data.shoppingCart[index]["addId"] = "add" + data.shoppingCart[index].id;
        data.shoppingCart[index]["minId"] = "min" + data.shoppingCart[index].id;
        data.shoppingCart[index]["inputId"] = "input" + data.shoppingCart[index].id;
    });
    return data;
}

function bindButtonAndInputEvent(id, number) {
    modifyInputAndSubtoalValue(id, number);
    modifyLocalData(id, number);
    modifyShopCarNumber();
    modifyTotalPrice();
}

function addCalcButtonClickEvent() {
    $("tr td div button").click(function () {
        var id = this.id.substring(3);
        var modifyNumber = getComputeNumber(id, this.innerHTML);
        bindButtonAndInputEvent(id, modifyNumber);
    })
}

function getComputeNumber(id, mark) {
    var number = parseInt($("#" + id + " .input").val());
    if (mark == "-") {
        return number - 1;
    }
    if (mark == "+") {
        return number + 1;
    }
}

function searchSameGood(shopGood , id) {
    for (var i = 0; i < shopGood.length; i++) {
        if (shopGood[i]["id"] == id) {
            return i;
        }
    }
    return shopGood.length;
}



function modifyInputAndSubtoalValue(id, number) {
    var inputId = "#" + id + " .input";
    $(inputId).val(number);

    var localInfo = getLocalData();
    var sameIndex = searchSameGood(localInfo, id);
    localInfo = localInfo[sameIndex];
    localInfo["count"] = $(inputId).val();

    var subTotalPrice = getSubtotalPrice(localInfo);
    $("#" + id + " .subtotal").text(subTotalPrice);

    if (localInfo["count"] == 0) {
        $("#" + id).remove();
    }
}

function modifyLocalData(id, number) {
    var local = getLocalData();
    var index = searchSameGood(local, id);
    local[index]["count"] = number;
    local[index]["subtotal"] = getSubtotalPrice(local[index]);
    if (local[index]["count"] == 0) {
        local.splice(index, 1);
    }
    window.localStorage.setItem("shoppingCart", JSON.stringify(local));
}

function getSubtotalPrice(info) {
    var beforPrice = info["count"] * info["price"];
    if ( info["count"] > 2 && info["discount"]==true ) {
        info["count"] = info["count"] - parseInt(info["count"] / 3);
        var realPrice = info["count"] * info["price"];
        return realPrice + "元(原价：" + beforPrice + "元)";
    }
    else {
        return beforPrice + "元";
    }
}



function modifyTotalPrice() {
    var localData = getLocalData();
    var total = 0;
    _.times(localData.length, function (i) {
        var index = localData[i]["subtotal"].indexOf("元");
        var subTotal = localData[i]["subtotal"].substring(0, index)
        total += parseFloat(subTotal);
    });
    $(".pay_div p b").text(total.toFixed(2) + '元');

}

function clickPayButton() {
    $(".pay_div button").click(function () {
        window.location.href = "../html/payPage.html";
    })
}


function bindInputKeyUp() {
    $("input").keyup(function() {
        var text = $(this).val();
        console.log(text);
        if (isNaN(text) || text == " ") {
            $(this).val("1");
        }
        if (text != "") {
            var id = this.id.substring(5);
            bindButtonAndInputEvent(id, parseInt($(this).val()));
        }

    });
}

function bindInputNotNull() {
    $("input").change(function() {
        console.log("listenInput");
        var text = $(this).val();
        var id = this.id.substring(5);
        if (text == "") {
            bindButtonAndInputEvent(id, 1);
        }
    })
}



//
//function getPageButton() {
//    var localData = getLocalData()==undefined ? [] : JSON.parse(getLocalData());
//    var template = $("#page_template").html();
//    _.times(localData.length / 10 + 1, function (index) {
//        var temp = template.replace(/page/, index + 1);
//        $("#jump_page").append(temp);
//    });
//}
